package inutan.gateway.balancer;

import org.ricks.common.exception.RunException;
import org.ricks.common.lang.Assert;
import org.ricks.net.AioSession;
import org.ricks.net.SessionManager;
import org.ricks.net.balancer.IConsumerLoadBalancer;

import java.util.Set;

/**
 * User%num 分配session
 */
public class ConsistentHashConsumerLoadBalancer implements IConsumerLoadBalancer {


    /**
     * 通过argument的toString计算一致性hash，所以传入的argument一般要能代表唯一性，比如用户的id
     *
     * @param argument 参数，一般要能代表唯一性，比如用户的id
     * @return 调用的session
     */
    @Override
    public AioSession loadBalancer(byte modularId, Object argument) {
        Assert.isNotNull(argument, "参数异常无法进行hash一致性负载均衡 ");
        Set<AioSession> sessions = SessionManager.me().get(String.valueOf(modularId));
        Assert.isFalse(sessions.isEmpty() ,"ModularId["+modularId+"] 未发现连接Gateway 逻辑节点，启动对应模块的逻辑节点！" );
        int index = Math.abs(argument.hashCode()) % sessions.size();
        return sessions.stream().toArray(AioSession[]::new)[index];
    }
}
